<template>
  <div class="page-container">
    <div class="in-container">
      <AppSearchForm @submit="getList" @reset="reset">
        <el-form-item>
          <label id="select_nation" for="top_name">名称：</label>
          <el-input
            id="top_name"
            style="width: 140px"
            v-model="query.ServiceProject"
            clearable
            placeholder="请输入服务名称"
          />
          <label class="service_label" for="select_service">适用业务：</label>
          <docSelects
            id="select_service"
            ref="select_service"
            v-model:modelData="modelData"
            clearable
            placeholder="请输入搜索"
            :option="this.options"
            @getOption="changeModelData"
            @modeType="clearServiceType"
            fit-input-width>
          </docSelects>
        </el-form-item>
      </AppSearchForm>
      <div class="btn-area">
        <el-button @click="openDialog" type="primary"> 新增 </el-button>
        <el-button @click="exportFile" type="primary"> EXCEL导出 </el-button>
        <el-button @click="deleteSelectData" type="danger"> 删除 </el-button>
      </div>
      <AppPageTable
        stripe
        :data="tableData.data"
        @change="getList()"
        :autostyle="'height: calc(100% - 80px);'"
        :option="tableData.option"
      >
        <el-table-column
          show-overflow-tooltip
          type="selection"
          width="55"
          fixed="left"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="serviceProject"
          width="100"
          label="名称"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="name"
          width="150"
          label="自定义名称"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          prop="serviceType"
          width="500"
          label="适用业务"
        />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button @click.stop="update(scope.row)" type="primary"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除本条数据吗？"
              @confirm="deleteData(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </AppPageTable>
      <el-dialog
        :title="dialogData.title"
        v-model="dialogData.show"
        width="500px"
      >
        <el-form
          :model="formData"
          :rules="formRules"
          label-width="80px"
          ref="form"
        >
          <el-form-item prop="serviceProject" label="服务项">
            <el-input v-model="formData.serviceProject"></el-input>
          </el-form-item>
          <el-form-item prop="name" label="名称">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item :rules="serviceTypeArr" prop="serviceType" label="适用业务">
            <muchSelects
              ref="muchSelects"
              v-model:modelData="formData.serviceTypeArr"
              :options="this.options"
              :placeholder="请选择"
              @getOption="handleChange"
              @changeServiceType="changeServiceType"
            ></muchSelects>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel" link>取消</el-button>
            <el-button type="primary" @click="submit"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import docSelects from "./../business/components/docSelects.vue";
// 引入多选框组件
import muchSelects from "./components/muchSelects.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import AppTitleBox from "@/components/AppTitleBox.vue";
import { fileDownload } from "@/public/publicUtils";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  components: {
    AppSearchForm,
    AppPageTable,
    AppTitleBox,
    docSelects,
    muchSelects
  },
  data() {
    return {
      query: {
        ServiceProject: "",
        ServiceType: "",
        PageIndex: 1,
        PageSize: 15,
        value: 0
      },
      loading: false,
      tableData: {
        data: [],
        option: useTableOption(),
      },
      dialogData: {
        show: false,
        title: "",
        btnLoading: false,
      },
      formData: {
        id: "",
        serviceProject: "",
        name: "",
        serviceType: "",
        value: 0, // 标签转换value,
        serviceTypeArr: []
      },
      formRules: {
        serviceProject: [
          { required: true, message: "请输入服务项", trigger: "blur" },
        ],
        name: [{ message: "请输入自定义名称", trigger: "blur" }],
        serviceType: [{
          required: true, message: "请输入适用业务", trigger: "blur"
        }]
      },
      options: [],
      modelData: ""
    };
  },
  methods: {
    async getList() {
      this.tableData.option.loading = true;

      await this.getService()

      this.$http.get("/api/base/serviceProject/query", {
          ServiceProject: this.query.ServiceProject,
          ServiceType: this.query.value==0?"":this.query.value,
          PageIndex: this.tableData.option.page,
          PageSize: this.tableData.option.pageSize
        }).then((res) => {
          this.tableData.data = res.content.map(item => {
            if (item.serviceType.length>1) {
              let str = ''
              let newServiceType = item.serviceType.split(',')
              for(let i = 0; i < this.options.length;i++) {
                for(let j = 0; j < newServiceType.length; j++) {
                  if (newServiceType[j]==this.options[i].value) {
                    str = str + `、${this.options[i].label}`
                  }
                }
              }
              item.serviceType = str.slice(1)
            } else {
              for(let i = 0;i<this.options.length;i++) {
                if (item.serviceType==this.options[i].value) {
                  item.serviceType = this.options[i].label
                }
              }
            }
            return item
          });
          this.tableData.option.total = res.totalElements;
        }).finally(() => {
          this.tableData.option.loading = false;
        });
    },
    async getService() {
      let res = await this.$http.get("/api/dict/query", {
        PageIndex: 1,
        PageSize: 9999,
        keyWords: "业务类型",
      });

      this.options = res.content[0].dictDetails.map(item => {
        item["selectLabel"] = item.label
        return item
      })
    },
    clearServiceItem() {
      this.formData.id = ""
      this.formData.serviceProject = ""
      this.formData.name = ""
      // 将服务项全部清空
      this.formData.serviceTypeArr = []
      this.formData.serviceType = ""
    },
    clearServiceType(data) {
      this.query.value = data
    },
    handleChange(data) {
      this.formData.serviceTypeArr = data
      this.formData.serviceType = data.map(item => {return Number(item)}).sort().join(',')
    },
    changeModelData(data) {
      this.query.value = this.translate(this.options,data.label)
    },
    translate(arr,label) {
        for(let i = 0;i<arr.length;i++) {
            if (arr[i].label==label) {
                return arr[i].value
            }
        }
    },
    reset() {
      this.tableData.option.page = 1;
      this.tableData.option.pageSize = 15;
      this.query.ServiceProject = "";
      this.query.value = 0
      // 重置适用业务下拉搜索框
      this.$refs.select_service.clearModelData()
      this.getList();
    },
    update(data) {
      this.clearServiceItem()
      console.log(data, 'data');

      if (data.serviceType.indexOf('、') > -1) {
        let newServiceType = data.serviceType.split('、')
        let set = new Set(this.formData.serviceTypeArr)
        for(let i = 0;i<this.options.length;i++) {
          for(let j = 0;j < newServiceType.length;j++) {
            if(newServiceType[j]==this.options[i].label) {
              set.add(this.options[i].value)
              this.formData.serviceType = this.formData.serviceType + (j==newServiceType.length-1 ? this.options[i].value:`${this.options[i].value},`)
            }
          }
        }
        this.formData.serviceTypeArr = Array.from(set).sort()
      } else {
        this.formData.serviceTypeArr.push(this.translate(this.options,data.serviceType))
        this.formData.serviceType = this.translate(this.options,data.serviceType)
      }
      this.formData.id = data.id
      this.formData.serviceProject = data.serviceProject
      this.formData.name = data.name

      this.dialogData.title = "编辑企业标签";
      this.dialogData.show = true;
      this.$refs.muchSelects.resetIsSelectAll()
    },
    deleteData(data) {
      this.$http.post("/api/base/serviceProject/delete", {
          idArray: [data.id],
        }).then((res) => {
          if (res.status) {
            this.$message.success(res.message);
            this.getList();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    async submit() {
      this.dialogData.btnLoading = true;
      await this.$refs.form.validate();

      if (this.formData.id) {
        this.$http.post("/api/base/serviceProject/edit", {
          id: this.formData.id,
          serviceProject: this.formData.serviceProject,
          name: this.formData.name,
          serviceType: this.formData.serviceType
        }).then((res) => {
            if (res.status) {
              this.$message.success(res.message);
              this.getList();
              this.dialogData.show = false;
            } else {
              this.$message.error(res.message);
            }
            this.dialogData.btnLoading = false;
          });
      } else {
        this.$http.post("/api/base/serviceProject/create", {
          serviceProject: this.formData.serviceProject,
          name: this.formData.name,
          serviceType: this.formData.serviceType
        }).then((res) => {
            if (res.status) {
              this.$message.success(res.message);
              this.getList();
              this.dialogData.show = false;
            } else {
              this.$message.error(res.message);
            }
            this.dialogData.btnLoading = false;
        });
      }
    },
    changeServiceType(data) {//适用业务全选功能
      console.log(data);
      if (data==[]) {
        this.formData.serviceType = ''
        this.formData.serviceTypeArr = []
      } else {
        this.formData.serviceType = data.join(',')
        this.formData.serviceTypeArr = data
      }
    },
    cancel() {
      this.dialogData.show = false;
    },
    openDialog() {
      this.clearServiceItem()
      this.dialogData.title = "新增服务项目";
      this.dialogData.show = true;
      this.$refs.muchSelects.resetIsSelectAll()
    },
    exportFile() {
      fileDownload("/api/base/serviceProject/download", this.query, "服务项目")
        .then(() => {})
        .catch((err) => {
          ElMessage.warning("文件导出失败");
        });
    },
    // 查询所有企业标签
    async getNation() {
      let res = await this.$http.get("/api/dict/query", {
        PageIndex: this.tableData.option.page,
        PageSize: this.tableData.option.pageSize,
        keyWords: "业务类型",
      });
      this.options = res.content[0].dictDetails.map(item => {
        item["selectLabel"] = item.label
        return item
      })
    },
    /**
     * 多项删除业务
     */
    deleteSelectData() {
      let deleteSelectArray = [];
      this.tableData.option.selected.forEach((t) =>
        deleteSelectArray.push(t.id)
      );
      ElMessageBox.confirm("确定删除所选服务项目", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
          this.$http.post("/api/base/serviceProject/delete", {
              idArray: deleteSelectArray,
            })
            .then((res) => {
              if (res.status) {
                this.$message.success(res.message);
                this.getList();
              } else {
                this.$message.error(res.message);
              }
            });
        }).catch(() => {
          this.$message.info("取消删除");
        });
    },
  },
  watch: {
    "dialogData.show"(newVal) {
      if (!newVal) {
        this.formData = {
          nationCode: "",
          nationName: "",
          nationEnName: "",
          customCode: "",
        };
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      }
    }
  },
  created() {
    this.getNation()
    this.getList();
  },
});
</script>

<style lang="scss" scoped>
.btn-area {
  margin-bottom: 8px;
}
.service_label {
  margin-left: 14px;
}
.form .el-select--small {
  width: 140px !important;
}
</style>
